package springframework.beans.factory.support;

import springframework.beans.BeansException;
import springframework.beans.factory.config.BeanDefinition;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzp
 * @Date:2023/3/10
 * @description:
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry {

	private Map<String, BeanDefinition> beanDefinitions = new HashMap<>();

	@Override
	public BeanDefinition getBeanDefinition(String beanName) {
		BeanDefinition beanDefinition = beanDefinitions.get(beanName);
		if (beanDefinitions == null) {
			throw new BeansException("No bean named '" + beanName + "' is defined");
		}
		return beanDefinition;
	}

	@Override
	public void registerBeanDefinition(String name, BeanDefinition beanDefinition) {
		beanDefinitions.put(name, beanDefinition);
	}

	@Override
	public Object getBean(String beanName, Object... args) throws BeansException {
		// 先走单例拿
		Object bean = getSingleton(beanName);
		if (bean != null) {
			return bean;
		}
		// 没有则进行注册
		BeanDefinition beanDefinition = getBeanDefinition(beanName);

		bean = createBeanInstance(beanName, beanDefinition, args);
		// 添加进单例对象缓存中
		addSingleton(beanName, bean);
		return bean;
	}
}
